import React from 'react'
import {fetch, post} from '../../../my_axios/api'
import {Row, Col, Icon, Button, Table, message, Modal, Form, Input,DatePicker} from 'antd'
import Search from './component/search_bar'
import './index.less'
import UserForm from './component/user_form'
import ChangeRolesModal from './component/change_roles_modal'
import PageTitle from '../../../components/PageTitle/index'
import {connect} from 'react-redux'
import createHistory from 'history/createHashHistory'
import BaseForm from './../../../components/BaseForm/index'
const history = createHistory();
const confirm = Modal.confirm;
const FormItem = Form.Item;
class User extends React.Component {

    constructor(props) {
        super(props);
        this.currentUserId = '';
        this.roles = [];
        this.formType = '';
        this.modalTitle = "";
        this.state = {
            test:'',
            selectedRowKeys:[],
            currentPage: 1,
            loading: true,
            userList: [],
            total_elements: 0,
            modalShow: false,
            modalRoleShow: false,
            roleIdArray: [],
            userParams:{
                role: '',
                name: '',
                size:10,
                page:0
            },
            userObject: {
                "name": "",
                "user_name": "",
                "password": "",
                "mobile": "",
                "email": ""
            },
            checkboxList: [],
            buttonList :[
                {
                    type: 'primary',
                    icon: 'plus',
                    isShow: false,
                    name: '新增1',
                    methodName: 'addUser'
                },
                {
                    type: 'primary',
                    icon: 'edit',
                    isShow: false,
                    name: '修改',
                    methodName: 'updateUser'
                },
                {
                    type: 'primary',
                    icon: 'eye-o',
                    isShow: false,
                    name: '读取',
                    methodName: 'getUser'
                },
                {
                    type: 'primary',
                    icon: 'user',
                    isShow: false,
                    name: '配置角色',
                    methodName: 'changeRoles'
                },
                {
                    type: 'primary',
                    icon: 'key',
                    isShow: false,
                    name: '修改密码',
                    methodName: 'updateKey'
                },
                {
                    type: 'danger',
                    icon: 'delete',
                    isShow: false,
                    name: '删除',
                    methodName: 'userDelete'
                },
            ],
            pagination:{  // 分页
                pageSize: 10,
                pagination: true,
                currentPage: 1,
                total:0,
                onChange: this.changePage.bind(this),
            },
            updateUserFormList:[
                {
                    type: 'INPUT',
                    label: '姓名',
                    field: 'name',
                    placeholder: '请输入姓名',
                    initialValue: '',
                    rule: true,
                    colLayout: {
                        xs: {span: 24},
                        sm: {span: 24},
                        md: {span: 24},
                        lg: {span: 24},
                        xl: {span: 24},
                    },
                    formItemLayout: {
                        labelCol: {
                            xs: {span: 5},
                            sm: {span: 5},
                            md: {span: 5},
                            lg: {span: 5},
                            xl: {span: 5},
                        },
                        wrapperCol: {
                            xs: {span: 19},
                            sm: {span: 19},
                            md: {span: 19},
                            lg: {span: 19},
                            xl: {span: 19},
                        },
                    }
                },
            ],
            updateUserPWDFormList:[
                {
                    type: 'INPUT',
                    label: '新密码',
                    field: 'new_password',
                    placeholder: '请输入密码',
                    initialValue: '',
                    rule: true,
                    colLayout: {
                        xs: {span: 24},
                        sm: {span: 24},
                        md: {span: 24},
                        lg: {span: 24},
                        xl: {span: 24},
                    },
                    formItemLayout: {
                        labelCol: {
                            xs: {span: 5},
                            sm: {span: 5},
                            md: {span: 5},
                            lg: {span: 5},
                            xl: {span: 5},
                        },
                        wrapperCol: {
                            xs: {span: 19},
                            sm: {span: 19},
                            md: {span: 19},
                            lg: {span: 19},
                            xl: {span: 19},
                        },
                    }
                },
            ],
            updateUserVisible:false,
            updateUserPWDVisible:false,
        };
    }
    componentDidMount() {
        this.getPermissionByPath();
        this.getUserList();
        this.getRoleList();
    };
    myQuery(name, role) {
        this.setState({
            userParams:{
                role:role,
                name:name,
                size:10,
                page:0
            },
        });
        this.getQueryUserList({name:name,role:role});
    }

    /**
     * 查询
     * @param params
     */
    getQueryUserList(params) {
        this.setState({
            loading: true
        });
        fetch('user/list', params).then(res => {
            if (res.status === 'success') {
                this.setState({
                    userList: res.data.content,
                    total_elements: res.data.total_elements,
                    currentPage: 1,
                    loading: false
                });
            } else {
                message.error(res.data.message);
            }
        }).catch(err => {
            console.log(err);
        });
    }

    /**
     * 用户列表
     * @param params
     */
    getUserList() {
        fetch('user/list',this.state.userParams).then(res => {
            if (res.status === 'success') {
                this.setState({
                    userList: res.data.content,
                    total_elements: res.data.total_elements,
                });
                this.setState({
                    loading: false
                })
            } else {
                message.error(res.data.message);
            }

        }).catch(err => {
            console.log(err);
        });
    }

    /**
     * 角色列表
     */
    getRoleList() {
        fetch('role/list').then(res => {
            if (res.status === 'success') {
                this.roles = res.data;
            } else {
                message.error(res.data.message);
            }

        }).catch(err => {
            console.log(err);
        })
    }

    /**
     * 根据权限获取按钮
     */
    getPermissionByPath() {
        let params = {
            route: '/user/list'
        };
        fetch('permission/children', params).then(res => {
            if (res.status === 'success') {
                let list=this.state.buttonList;
                for (let permission of res.data) {
                    for (let button of list) {
                        if (permission.name === button.name) {
                            if (permission.name === '读取') {
                                button.name = '查看'
                            }
                            button.isShow = true;
                        }
                    }
                }
                this.setState({
                    buttonList:list
                })

            } else {
                message.error(res.data.message);
                window.localStorage.setItem('token',null);//无效？
                history.push('/login')
            }
        }).catch(err => {
            console.log(err);
        })
    }

    /**
     * 分页
     */
    changePage(page) {
        this.setState({
            pagination:
                {
                    ...this.state.pagination,
                    currentPage:page
                }
            // currentPage: page,
        });
        let params = {
            name: this.state.userParams.name,
            role: this.state.userParams.role,
            page: page - 1
        };
        this.getUserList(params)
    }
    /**
     * 操作按钮
     */
    buttonMethods(name) {
        if (name !== 'addUser' && (this.currentUserId === '' || this.currentUserId === undefined)) {
            message.error('请选择用户');
        } else {
            if (name === 'changeRoles') {
                this.formType = '配置角色';
                this.getUserById();
            } else if (name === 'addUser') {
                this.modalTitle = '新增用户';
                this.formType = '新增';
                this.setState({modalShow: true})
            } else if (name === 'updateUser') {
                this.formType = '修改';
                this.getUserById();

            } else if (name === 'userDelete') {
                this.showDeleteConfirm();
            } else if (name === 'getUser') {
                this.modalTitle = '查看用户';
                this.formType = '查看';
                this.getUserById();
            }else if(name==='updateKey'){
                this.setState({
                    updateUserPWDVisible:true
                })
            }
        }
    }

    /**
     * 根据id获得用户信息
     */
    getUserById() {
        fetch('user/get', {id: this.currentUserId}).then(res => {
            if (res.status === 'success') {
                if(this.formType=='修改'){
                    this.setState({
                            updateUserFormList:[
                                {
                                    ...this.state.updateUserFormList[0],
                                    initialValue:res.data.name
                                },
                            ]
                        },()=>{
                            this.setState({
                                updateUserVisible:true
                            })
                        }
                    )
                }else {
                    let array = [];
                    let roleIdArray = [];
                    for (let role of res.data.roles) {
                        array.push(role.name);
                        roleIdArray.push(role.id);
                    }
                    this.setState({
                        roleIdArray: roleIdArray
                    });
                    res.data.rolesString = array.toString();
                    this.setState({
                        userObject: res.data
                    });
                    if (this.formType === '查看') {
                        this.setState({modalShow: true})
                    }  else if (this.formType === '配置角色') {
                        //角色列表checkbox
                        let checkboxList = [];
                        let index = 0;
                        for (let role of this.roles) {
                            let item = {
                                name: role.name,
                                value: role.id,
                                checked: false,
                                index: index
                            };
                            checkboxList.push(item)
                            index++;
                        }
                        this.setState({
                            checkboxList: checkboxList
                        });
                        //当前用户已有角色
                        for (let checkbox of  this.state.checkboxList) {
                            for (let userRoleId of  this.state.roleIdArray) {
                                if (checkbox.value === userRoleId) {
                                    checkbox.checked = true;
                                }
                            }
                        }
                        this.refs.rolesModalRef.setRoleIdArray(this.state.roleIdArray)
                        this.setState({modalRoleShow: true})
                    }
                }

            } else {
                message.error(res.data.message);
            }

        }).catch(err => {
            console.log(err);
        })
    }

    /**
     * 提交表单 前端(调用子组件方法)
     */
    addUserHandleOk() {
        this.formRef.handleSubmit();
    }
    addUserHandleCancel() {
        this.restoreData();
        this.setState({
            modalShow: false,
        });
    }

    deleteUserHandleOk=()=>{
        post('user/delete', {id: this.currentUserId}).then(res => {
            if (res.status === 'success') {
                message.success('删除成功');
                this.emptyData();
                this.getUserList();
                this.currentUserId='';
            } else {
                message.error(res.data.message);
            }
        }).catch(err => {
            console.log(err);
        })
    }

    roleHandleCancel() {
        this.setState({
            modalRoleShow: false,
        });
    }
    roleHandleOk() {
        let array=this.state.roleIdArray;
        //配置角色提交
        if (array.length === 0) {
            message.error("至少选择一个角色")
        } else {
            let params = {
                id: this.currentUserId,
                roles: array.toString()
            };
            post('user/change_roles', params).then(res => {
                if (res.status === 'success') {
                    message.success('配置成功');
                    this.setState({
                        modalRoleShow: false
                    });
                    this.getUserList();
                } else {
                    message.error(res.data.message);
                }
            }).catch(err => {
                console.log(err);
            })
        }
    }

    /**
     * 提交表单 后端
     */
    submitForm(value) {
        if (this.formType === '新增') {
            let params = {
                "name": value.name,
                "user_name": value.user_name,
                "password": value.password,
            };
            post('user/create', params).then(res => {
                if (res.status === 'success') {
                    this.addUserHandleCancel();
                    message.success('新增成功');
                    this.restoreData();
                    this.getUserList();
                } else {
                    message.error(res.data.message);
                }

            }).catch(err => {
                console.log(err);
            })
        }
    }
    onRowClick=(record,index)=>{
        let selectedKey=[record.id];
        this.currentUserId=record.id;
        this.setState({
            selectedRowKeys:selectedKey,
        });
    };

    restoreData() {
        if (this.formType !== '删除') {
            this.formRef.resetFields();
        } else {
            this.currentUserId = '';
        }
        this.setState({
            userObject: {
                "name": "",
                "user_name": "",
                "password": "",
                "mobile": "",
                "email": ""
            }
        });
    }

    roleIdArrayOnChange(checkedValues){
        this.setState({
            roleIdArray:checkedValues
        })
    }
    handleOk=()=>{
        this.updateUserFormRef.handleFormSubmit();
    }
    handleCancel=()=>{
        this.emptyData();
        this.setState({
            updateUserVisible: false,
        });
    };
    handleOkUserPWD=()=>{
        this.updateUserPWDFormRef.handleFormSubmit();
    };
    handleCancelUserPWD=()=>{
        this.setState({
            updateUserPWDVisible: false,
        });
    };
    handleForm = (fieldsValue) => {
        let params = {
            "id": this.currentUserId,
            "name": fieldsValue.name,
            "mobile": fieldsValue.mobile,
            "email": fieldsValue.email,
        };
        post('user/update_by_admin', params).then(res => {
            if (res.status === 'success') {
                message.success('修改成功');
                this.setState({
                    updateUserVisible: false
                })
                this.getUserList();
            } else {
                message.error(res.data.message);
            }
        }).catch(err => {
            console.log(err);
        })
    };
    /**
     *修改密码
     */
    handleUserPWDForm=(fieldsValue)=>{
        let params = {
            "id": this.currentUserId,
            "new_password": fieldsValue.new_password,
        };
        post('user/change_password_by_admin', params).then(res => {
            if (res.status === 'success') {
                message.success('修改成功');
                this.setState({
                    updateUserPWDVisible: false
                });
            } else {
                message.error(res.data.message);
            }
        }).catch(err => {
            console.log(err);
        })
    };
    showDeleteConfirm = () => {
        let _this = this;
        confirm({
            title: '提示',
            content: '确定要删除？',
            okText: '确认',
            cancelText: '取消',
            onOk() {
                _this.deleteUserHandleOk()
            },
            onCancel() {

            },
        });
    }
    /**
     * 清除数据
     */
    emptyData() {
        let list = [];
        this.state.updateUserFormList.map((item) => {
            item.initialValue = '';
            list.push(item);
        });
        this.setState({
            updateUserFormList: list
        });
    };
    render() {
        const selectedRowKeys=this.state.selectedRowKeys;
        const rowSelection={
            type:'radio',//单选
            selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.currentUserId = `${selectedRowKeys}`;
                this.setState({
                    selectedRowKeys:selectedRowKeys,
                });
            },
        };
        return (
            <div style={{padding:10,background:'white'}}>
                <PageTitle
                    title="用户管理"
                    buttonMethods={this.buttonMethods.bind(this)}
                    buttonList={this.state.buttonList}
                />
                <Search ref="search" roles={this.roles} callback={this.myQuery.bind(this)}></Search>
                <Table rowSelection={rowSelection}
                       scroll={{ x: 650}}
                       onRow={(record,index) => {
                           return {
                               onClick:()=>{
                                   this.onRowClick(record,index);
                               }
                           };
                       }}
                       size='small'
                       loading={this.state.loading}
                       dataSource={this.state.userList}
                       columns={columns}
                       rowKey="id"
                       pagination={{  // 分页
                           pageSize: 10,
                           pagination: true,
                           hideOnSinglePage:true,
                           current: this.state.currentPage,
                           total: this.state.total_elements,
                           onChange: this.changePage.bind(this),
                       }}
                       bordered
                />
                <Modal
                    width={400}
                    destroyOnClose={true}
                    title={this.modalTitle}
                    visible={this.state.modalShow}
                    onCancel={this.addUserHandleCancel.bind(this)}
                    footer={this.formType !== '查看' ?
                        [
                            <Button key="back" onClick={this.addUserHandleCancel.bind(this)}>取消</Button>,
                            <Button key="submit" type="primary" htmlType="submit"
                                    onClick={this.addUserHandleOk.bind(this)}>
                                提交
                            </Button>,
                        ] : null}>
                    <div style={{paddingRight:20}}>
                        <UserForm  wrappedComponentRef={(inst) => this.formRef = inst}
                                   userObject={this.state.userObject}
                                   formType={this.formType}
                                   modalCallback={this.submitForm.bind(this)}
                        ></UserForm>
                    </div>

                </Modal>
                <Modal
                    width={400}
                    title='修改用户'
                    visible={this.state.updateUserVisible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    destroyOnClose={true}
                    okText="确认"
                    cancelText="取消"
                >
                    <Row style={{paddingRight: 20,paddingTop:20}}>
                        <BaseForm
                            wrappedComponentRef={(inst) => this.updateUserFormRef = inst}
                            formList={this.state.updateUserFormList}
                            formSubmit={this.handleForm}></BaseForm>
                    </Row>
                </Modal>
                <Modal
                    width={400}
                    title='修改密码'
                    visible={this.state.updateUserPWDVisible}
                    onOk={this.handleOkUserPWD}
                    onCancel={this.handleCancelUserPWD}
                    destroyOnClose={true}
                    okText="确认"
                    cancelText="取消"
                >
                    <Row style={{paddingRight: 20,paddingTop:20}}>
                        <BaseForm
                            wrappedComponentRef={(inst) => this.updateUserPWDFormRef = inst}
                            formList={this.state.updateUserPWDFormList}
                            formSubmit={this.handleUserPWDForm}></BaseForm>
                    </Row>
                </Modal>
                <ChangeRolesModal
                    ref="rolesModalRef"
                    checkboxList={this.state.checkboxList}
                    roleHandleCancel={this.roleHandleCancel.bind(this)}
                    roleHandleOk={this.roleHandleOk.bind(this)}
                    roleIdArrayOnChange={this.roleIdArrayOnChange.bind(this)}
                    roleIdArray={this.state.roleIdArray}
                    modalRoleShow={this.state.modalRoleShow}
                ></ChangeRolesModal>
            </div>
        )
    }
}
const columns = [
    {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
    }, {
        title: '用户名',
        dataIndex: 'user_name',
        key: 'user_name',
    },
    {
        title: '角色',
        dataIndex: 'rolesString',
        key: 'rolesString',
        render: (text, row, index) => {
            if (row.roles.length !== 0) {
                return <div>{row.roles[0].name}</div>;
            } else {
                return <div></div>;
            }
        },
    },

];
export default connect()(User)

